<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>商品购物车</title>
  </head>
  <body>
    <div id="app">
        <h3>商品购物车</h3>
      <table>
        <thead>
          <tr>
              <label>
                <input type="checkbox" v-model="selectAll">全选
                <input type="checkbox" v-model="selectNo">反选
              </label>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in itemList" :key="item.id">
            <td>
              <label>
                <input type="checkbox" v-model="item.selected">
              </label>
              {{ item.name }}  ￥  {{ item.price }}
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <button @click="subtract(index)" :disabled="item.quantity === 1">-</button>
              数量：{{ item.quantity }}
              <button @click="add(index)">+</button>
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              小计：{{ item.price * item.quantity }}</td>
          </tr>
        </tbody>
      </table>
      <div>
        <span align="right">总价：{{ totalPrice }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<button type="button"  @click="save" >提交订单</button></span>
      </div>
    </div>
    <script src="https://unpkg.com/vue@next"></script>
    <script>
      const app = Vue.createApp({
        data() {
          return {
            itemList: [
              { id: 1, name: '商品 1', price: 100, quantity: 1, selected: false },
              { id: 2, name: '商品 2', price: 200, quantity: 1, selected: false },
              { id: 3, name: '商品 3', price: 300, quantity: 1, selected: false }
            ],
            selectAll: false
          }
        },
        computed: {
          selectedItemCount() {
            return this.itemList.filter(item => item.selected).length
          },
          totalPrice() {
            return this.itemList.reduce((total, item) => {
              if (item.selected) {
                total += item.price * item.quantity
              }
              return total
            }, 0)
          }
        },
        methods: {
          add(index) {
            this.itemList[index].quantity++
          },
          subtract(index) {
            if (this.itemList[index].quantity > 1) {
              this.itemList[index].quantity--
            }
          }
        },
        watch: {
          selectAll(val) {
            this.itemList.forEach(item => item.selected = val)
          },
          itemList: {
            handler(val) {
              this.selectAll = val.every(item => item.selected)
            },
            deep: true
          }
        }
      })

      app.mount('#app')
    </script>
  </body>
</html>